package com.nbstar.film.spider.spider;

import com.nbstar.film.spider.filter.*;
import com.nbstar.film.spider.http.SipderStringRequest;
import com.nbstar.film.spider.pojo.FilmInfo;
import com.nbstar.film.spider.filter.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.URLDecoder;
import java.net.URLEncoder;

@Slf4j
public class IqiyiSpider extends BaseSpider{
    //private static Logger logger = LoggerFactory.getLogger(IqiyiSpider.class);

    public IqiyiSpider() {
        this.spiderName = "IQiYi";
        setRequest(new SipderStringRequest());
        registFilter(new ReplaceBracketsNameFilter());
        registFilter(new ReplaceBlankNameFilter());
        registFilter(new ReplaceCHColonNameFilter());
        registFilter(new ReplaceChCommaNameFilter());
        registFilter(new ReplaceCHDotNameFilter());
        registFilter(new ReplaceColonNameFilter());
        registFilter(new ReplaceCommaNameFilter());
        registFilter(new ReplaceCHQuotesNameFilter());
        registFilter(new ReplaceQuotesNameFilter());
    }

    @Override
    public String getContentId(String filmName) throws Exception {
        return URLEncoder.encode(filmName);
    }

    @Override
    public FilmInfo getFilmInfo(String contentID) throws Exception {
        String url = "https://so.iqiyi.com/so/q_" + contentID;
        //String url = "https://so.iqiyi.com/so/q_%E8%80%81%E5%B8%88%C2%B7%E5%A5%BD?source=input&sr=721778965362817&ssrt=20200918103045421&ssra=c404858bab03cd41b62dd7c4aa0efdb3";
        FilmInfo filmInfo = new FilmInfo();
        //String html = getRequest().getHtml(url);
        String html = firefoxDriverRequest.getHtml(url);
        //System.out.println(html);
        Document doc = Jsoup.parse(html);

        Elements figure = doc.getElementsByClass("result-figure");
        if (figure.size() == 0) {
            log.error("Cant  not get result-figure {}", URLDecoder.decode(contentID));
        } else {
            Element f = figure.first();
            Elements icon_tr = f.getElementsByClass("icon-tr");
            if (icon_tr.size() > 0) {
                Element icon = icon_tr.first();
                String style = icon.attr("style");
                System.out.println("style:" + style);
                if (StringUtils.isEmpty(style)) {
                    filmInfo.setNeedVip(true);
                }

            }
        }

        Elements result = doc.getElementsByClass("result-right");
        if (result.size() == 0) {
            log.error("Can not get result-right {}", URLDecoder.decode(contentID));
            return  filmInfo;
        }

        for (Element e : result) {
            Elements links = e.select("a[href]");
            if (links.size() == 0) {
                continue;
            }

            String name = parseName(links.get(0).attr("title"));
            String href = "https:" + links.get(0).attr("href").trim();

            if (name.equals(URLDecoder.decode(contentID))) {
                Elements year = e.getElementsByClass("year");
                if (year.size() > 0) {
                    filmInfo.setArriveDate(year.get(0).text());
                }

                Elements score = e.getElementsByClass("score");
                if (score.size() > 0) {
                    try {
                        filmInfo.setAverage(Double.parseDouble(score.get(0).text()));
                    } catch (Exception ex) {

                    }
                } else {
                    html = getRequest().getHtml(href);
                    Document detailsDoc = Jsoup.parse(html);
                    Elements effects = detailsDoc.getElementsByClass("effect-score");
                    if (effects.size() > 0) {
                        filmInfo.setAverage(Double.parseDouble(effects.text()));
                    }
                }

                Elements infos = e.getElementsByClass("qy-search-result-info half");
                for (Element info : infos) {
                    if (info.text().contains("导演:")) {
                        Elements directors = info.select("a[href]");
                        String direct = "";
                        int i = 0;
                        for (Element dir : directors) {
                            if (i<directors.size() - 1) {
                                direct += dir.text().trim() + ",";
                            } else {
                                direct += dir.text().trim();
                            }
                            i++;
                        }

                        filmInfo.setDirector(direct);

                    }

                    if (info.text().contains("地区:")) {
                        filmInfo.setArriveAddress(info.text().replace("地区:", "").trim());
                    }

                    if (info.text().contains("上映时间:")) {
                        filmInfo.setArriveDate(info.text().replace("上映时间:",  "").trim());
                    }

                    if (info.text().contains("主演:")) {
                        Elements actors = info.select("a[href]");
                        String actList = "";
                        int i = 0;
                        for (Element atc : actors) {
                            if (i<actors.size() -1 ) {
                                actList += atc.text().trim() + ",";
                            } else {
                                actList += atc.text().trim();
                            }
                            i++;
                        }

                        filmInfo.setActor(actList);
                    }
                    System.out.println(info.text());
                }

                Elements infoDes = e.getElementsByClass("info-des");
                if (infoDes.size() > 0) {
                    filmInfo.setDesc(infoDes.text());
                }

                Elements album = e.getElementsByClass("album-item");
                int max = 1;
                for (Element alb : album) {
                    String txtAlb = alb.text().trim();
                    if (txtAlb.contains("...")) {
                        continue;
                    }

                    int iAlb = Integer.parseInt(txtAlb);
                    if (iAlb > max) {
                        max = iAlb;
                    }
                }

                filmInfo.setPartNum(max + "");

                //filmInfo.setAliasName(e.getElementsByClass());
            }
        }
        filmInfo.setSuccess(true);
        return filmInfo;
    }
}
